<?php defined('SYSPATH') or die('No direct script access.');

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2020/09/25 14:56
 * Desc: 特产模块
 */
class Model_Api_V2_Techan
{

    public static $type_id = 118;

    public static $pay_name = array(
        '1' => '全款支付',
        '2' => '定金支付',
        '3' => '二次确认',
    );

    /**
     * @function 获取特产列表
     * @param $params
     * @param $keyword
     * @param int $page
     * @param int $pagesize
     * @return array
     */
    public static function search($params, $keyword = '', $page = 1, $pagesize = 10)
    {
        $sort_type = Arr::get($params, 'sort_type', '');
        $dest_py = Arr::get($params, 'dest_py', '');
        $attr_id = Arr::get($params, 'attrs', '');
        $price_id  = Arr::get($params, 'price_id', 0);


        $builder = DB::select(DB::expr('`sline_techan`.*,(IFNULL(`sline_techan`.bookcount,0)+IFNULL(`sline_member_order_statistic`.sell_num,0)) AS sell_num'))
            ->from('techan');

        //按目的地搜索
        if ($dest_py && $dest_py != 'all') {
            $dest_id = Model_Destinations::get_id_by_pinyin($dest_py);
        }

        //排序
        $order_by = "";
        if (!empty($sort_type)) {
            switch ($sort_type) {
                case 1: //价格升序
                    $order_by = "  sline_techan.price ASC,";
                    break;
                case 2:  //价格降序
                    $order_by = "  sline_techan.price DESC,";
                    break;
                case 3:  //销量降序
                    $order_by = " sell_num DESC,";
                    break;
                case 4: //推荐
                    $order_by = " sline_techan.shownum DESC,";
                    break;
                default:
                    break;
            }
        }

        if (!empty($dest_id)) {
            $builder->join('kindorderlist', 'left')
                ->on('techan.id', '=', DB::expr('`sline_kindorderlist`.aid'))
                ->on('techan.webid', '=', DB::expr('`sline_kindorderlist`.webid'))
                ->on('kindorderlist.typeid', '=', self::$type_id)
                ->on('kindorderlist.classid', '=', DB::expr("{$dest_id}"));
            $order_by .= "IFNULL(`sline_kindorderlist`.displayorder,9999) ASC,";
        } else {
            $builder->join('allorderlist', 'left')
                ->on('techan.id', '=', DB::expr('`sline_allorderlist`.aid'))
                ->on('techan.webid', '=', DB::expr('`sline_allorderlist`.webid'))
                ->on('allorderlist.typeid', '=', self::$type_id);
            $order_by .= "IFNULL(`sline_allorderlist`.displayorder,9999) ASC,";
        }

        // 需要提前处理真实购买量
        $builder->join('member_order_statistic', 'left')
            ->on('member_order_statistic.product_id', '=', DB::expr('`sline_techan`.id'))
            ->on('member_order_statistic.type_id', '=', self::$type_id);

        $builder->where('techan.ishidden', '=', 0)->where('techan.status', '=', 3);
        if (!empty($dest_id)) {
            $builder->and_where(DB::expr(" AND FIND_IN_SET('$dest_id',sline_techan.kindlist) "));
        }

        //价格区间
        if (!empty($price_id)) {
            $price_arr = DB::select()
                ->from('techan_pricelist')
                ->where('id', '=', $price_id)
                ->execute()
                ->current();
            if (!empty($price_arr)) {
                $builder->and_where(DB::expr(" AND sline_techan.price BETWEEN {$price_arr['lowerprice']} AND {$price_arr['highprice']}"));
            }
        }
        //关键词
        if (!empty($keyword)) {
            $builder->and_where('techan.title', 'like', '%' . $keyword . '%');
        }

        //按属性
        if (!empty($attr_id)) {
            $attr_where = self::get_attr_where($attr_id);
            if ($attr_where) {
                $builder->and_where(DB::expr($attr_where));
            }
        }

        $total = $builder->execute()->count();

        if ($page && $pagesize) {
            $offset = St_Page::offset($page, $pagesize);
            $builder->offset($offset)->limit($pagesize);
        }

        $builder->order_by(DB::expr("{$order_by}sline_techan.modtime DESC,sline_techan.addtime DESC"));
        $list = $builder->execute()->as_array();

        return array(
            'total' => $total,
            'list' => $list,
            'is_finished' => count($list) < $pagesize //是否还有更多的数据
        );
    }

    /**
     * 属性生成where条件,用于多条件属性搜索.
     * @param $attr_id
     * @return string
     */
    public static function get_attr_where($attr_id)
    {
        $data = Common::remove_arr_empty(explode('_', $attr_id));
        $str  = '';
        foreach ($data as $value) {
            $value = intval($value);
            if ($value != 0) {
                $str .= " and FIND_IN_SET($value,sline_techan.attrid) ";
            }
        }
        return $str;
    }

    /**
     * 特产详情
     * @param $id
     * @return array
     * @throws Exception
     */
    public static function detail($id)
    {
        $info = DB::select()->from('techan')->where('id', '=', $id)->execute()->current();
        if (!$info) {
            throw new Exception('产品不存在');
        }
        return $info;
    }

    /**
     * @function 获取特产内容栏目
     * @param $params
     * @return array
     */
    public static function get_content($params)
    {
        $default = array(
            'typeid' => '',
            'productinfo' => 0,
            'onlyrealfield' => 0,
            'pc' => 0

        );
        $params  = array_merge($default, $params);
        extract($params);

        $table         = 'sline_techan_content';
        $extend_tables = 'sline_techan_extend_field';

        $sql = "SELECT columnname,chinesename,isrealfield FROM {$table} ";
        $sql .= "WHERE webid=0 and isopen=1 ";
        $sql .= "ORDER BY displayorder ASC";
        $arr = DB::query(1, $sql)->execute()->as_array();

        //扩展表数据
        $productid = $productinfo['id'];//产品id
        $sql       = "SELECT * FROM $extend_tables WHERE productid='$productid'";
        $ar        = DB::query(1, $sql)->execute()->as_array();
        $list      = array();
        foreach ($arr as $v) {
            if ($v['columnname'] == 'tupian') {
                continue;
            }
            $content = !empty($productinfo[$v['columnname']]) ? $productinfo[$v['columnname']] : $ar[0][$v['columnname']];
            $content = $content ? $content : '';

            if (empty($content)) continue;

            $a                = array();
            $a['columnname']  = $v['columnname'];
            $a['chinesename'] = $v['chinesename'];

            $a['content'] = Model_Api_V2_Xcx::filter_content($content);
            $list[]       = $a;
        }
        return $list;
    }

    /**
     * @desc 获取套餐列表
     * @param $productid
     * @return mixed
     */
    public static function suit($productid)
    {
        $pay_name = array(
            '1' => '全款支付',
            '2' => '定金支付',
            '3' => '二次确认',
        );

        $suit = DB::select()->from('techan_suit')
            ->where('productid', '=', $productid)
            ->order_by('displayorder', 'ASC')
            ->execute()
            ->as_array();
        foreach ($suit as &$r) {
            $r['price']        = Model_Techan::get_minprice($productid, array('suitid', $r['id']));
            $r['title']        = $r['suitname'];
            $r['paytype_name'] = $pay_name[$r['paytype']];
        }
        return $suit;
    }

    /**
     * @function 获取运费
     * @param $param
     * @return array
     */
    public static function get_express_fee($param)
    {
        $suit_id   = $param['suit_id'];
        $addressid = $param['addressid'];
        $province  = $param['province'];
        $city      = $param['city'];
        $dingnum   = intval($param['dingnum']);

        $suit_info = DB::select()->from('techan_suit')->where('id', '=', $suit_id)->execute()->current();
        $freightid = $suit_info['freightid'];

        if (!empty($addressid)) {
            $plan_result = Model_Express_Plan::get_plan($freightid, $addressid);
        } else {
            $plan_result = Model_Express_Plan::get_plan_by_address($freightid, $province, $city);
        }

        if ($plan_result['status'] == 0) {
            return $plan_result;
        }
        $price = Model_Express_Plan::get_freight_price($suit_info, $plan_result['data'], $dingnum);
        return array('status' => true, 'price' => $price, 'express_plan' => $plan_result);
    }

    /**
     * 获取套餐列表
     * @param $product_id
     * @param $suit_id
     * @param $card_suit_id
     * @return array
     */
    public static function get_suits($product_id, $suit_id = null, $card_suit_id = null)
    {
        $query = DB::select()
            ->from('techan_suit')
            ->where('productid', '=', $product_id);

        if ($suit_id) {
            $query = $query->and_where('id', '=', $suit_id);
        }
        if ($card_suit_id) {
            $query = $query->and_where('id', 'IN', explode(',', $card_suit_id));
        }
        return $query->order_by(DB::expr('ifnull(displayorder,9999)'), 'asc')->execute()->as_array();
    }

    /**
     * 获取筛选的属性列表
     * @return array
     */
    public static function get_attributes()
    {
        $data = self::get_attributes_by_pid();
        foreach ($data as &$row) {
            $row['child'] = self::get_attributes_by_pid($row['id']);
        }
        return $data;
    }

    /**
     * @return array
     * 价格分类
     */
    public static function price_filter()
    {
        $data = DB::select('id', 'lowerprice', 'highprice')
            ->from('techan_pricelist')
            ->where('lowerprice', '>=', 0)
            ->order_by('lowerprice', 'asc')
            ->execute()
            ->as_array();
        foreach ($data as &$row) {
            if ($row['lowerprice'] == 0 && $row['highprice'] != 0) {
                $row['name'] = Currency_Tool::symbol() . $row['highprice'] . '以下';
            } else if ($row['highprice'] == '' || $row['highprice'] == 0) {
                $row['name'] = Currency_Tool::symbol() . $row['lowerprice'] . '以上';
            } else if ($row['lowerprice'] != '' && $row['highprice'] != '') {
                $row['name'] = Currency_Tool::symbol() . $row['lowerprice'] . '-' . Currency_Tool::symbol() . $row['highprice'];
            }
        }
        return $data;
    }

    /**
     * 通过父级id获取属性
     * @param $pid
     * @return array
     */
    public static function get_attributes_by_pid($pid = 0)
    {
        return DB::select('id', array('attrname', 'name'))
            ->from('techan_attr')
            ->where('pid', '=', $pid)
            ->and_where('isopen', '=', 1)
            ->order_by(DB::expr('ifnull(displayorder,9999)'), 'asc')
            ->execute()
            ->as_array();
    }

    /**
     * 创建订单数据
     * @param $request_param
     * @param $user_info
     * @return array
     * @throws Exception
     */
    public static function make_order($request_param, $user_info)
    {
        $member_id = $request_param['mid'];

        $suitid = $request_param['suitid'];
        //联系人
        $linkman = $request_param['linkman'];
        //手机号
        $linktel = $request_param['linktel'];

        $linkemail = $request_param['linkemail'];
        //备注信息
        $remark = Common::remove_xss($request_param['remark']);
        //产品id
        $id = intval($request_param['productid']);
        //预订数量
        $dingnum = intval($request_param['dingnum']);
        // 积分
        $needJifen = intval($request_param['needjifen']);
        // 快递计划id
        $express_plan_id = intval($request_param['express_plan_id']);
        // 邮寄地址信息
        $province = Common::remove_xss($request_param['receive_province']);
        $city     = Common::remove_xss($request_param['receive_city']);

        $source = Arr::get($request_param, 'source', 3);

        // 查询特产产品信息
        $info = DB::select()->from('techan')
            ->where('id', '=', $id)
            ->execute()
            ->current();
        if (!$info) {
            throw new Exception('产品不存在');
        }

        //下架状态判断
        if ($info['status'] != 3 || $info['ishidden'] == 1) {
            throw new Exception('当前产品已下架，不可预订');
        }

        // 查询套餐信息
        $suit = DB::select()->from('techan_suit')
            ->where('id', '=', $suitid)
            ->execute()
            ->current();
        if (empty($suit)) {
            throw new Exception('套餐不存在');
        }

        // 库存检查
        if (!Model_Techan::check_storage($id, $dingnum, $suitid)) {
            throw new Exception('套餐库存不足');
        }

        $suit['dingjin'] = Currency_Tool::price($suit['dingjin']);
        $suit['price']   = Currency_Tool::price($suit['price']);

        $info['status']    = 1;
        $info['name']      = $info['title'];
        $info['suit_name'] = $suit['suitname'];
        $info['price']     = $suit['price'];

        // 创建订单编号
        $ordersn = Product::get_ordersn(self::$type_id);

        //积分抵现
        $jifentprice = 0;
        $useJifen    = 0;
        if ($needJifen) {
            $jifentprice = Model_Jifen_Price::calculate_jifentprice($info['jifentprice_id'], self::$type_id, $needJifen, $user_info);
            $useJifen    = empty($jifentprice) ? 0 : 1;
            $needJifen   = empty($jifentprice) ? 0 : $needJifen;
        }

        //积分评论
        $jifencomment_info = Model_Jifen::get_used_jifencomment(self::$type_id);
        $jifencomment      = empty($jifencomment_info) ? 0 : $jifencomment_info['value'];

        // 快递费用计算
        $receiver_address_id = Arr::get($request_param, 'receive_id', 0);
        if ($receiver_address_id) {
            if (!Model_Member_Address::check_address_id($member_id, $receiver_address_id)) {
                $receiver_address_id = 0;
            }
        }
        $express_total_price = 0;
        if (!empty($suit['freightid'])) {
            if (!empty($user_info)) {
                $plan_info = Model_Express_Plan::get_plan($suit['freightid'], $receiver_address_id);
            } else {
                $plan_info = Model_Express_Plan::get_plan_by_address($suit['freightid'], $province, $city);
            }

            if ($plan_info['status'] == 0 || $plan_info['data']['id'] != $express_plan_id) {
                $plan_error = $plan_info['msg'] ?? '';
                throw new Exception('快递信息有误,' . $plan_error);
            }
            $express_price       = Model_Express_Plan::get_freight_price($suit, $plan_info['data'], $dingnum);
            $express_total_price = floatval($express_price);
        }

        // 自动关闭时间
        $auto_close_time = $suit['auto_close_time'] ?: 0;
        if ($auto_close_time) {
            $auto_close_time = $auto_close_time + time();
        }

        $auto_confirm_time = $suit['auto_confirm_time'] ?: 0;
        if ($auto_confirm_time) {
            $auto_confirm_time = $auto_confirm_time + time();
        }

        //自动退款时限
        $use_date=trim($request_param['use_date']);
        $no_confirm_refund = $suit['no_confirm_refund'] ?: 0;
        if ($no_confirm_refund) {
            $no_confirm_refund = strtotime($use_date . ' +1 day') -  $no_confirm_refund ;
        }

        $receiver_address_info = Db::select('province', 'city', 'area', 'receiver', 'phone', 'postcode', 'address')
            ->from('member_address')
            ->where('id', '=', $receiver_address_id)
            ->execute()
            ->current();

        return array(
            'ordersn' => $ordersn,
            'webid' => 0,
            'typeid' => self::$type_id,
            'productautoid' => $id,
            'productaid' => $info['aid'],
            'productname' => $info['name'],
            'suit_name' => $info['suit_name'],
            'litpic' => $info['litpic'],
            'price' => $info['price'],
            'childprice' => 0,
            'jifentprice' => $jifentprice,
            'jifenbook' => $info['jifenbook_id'],
            'jifencomment' => $jifencomment,
            'paytype' => 1,
            'dingjin' => '',
            'usedate' => '',
            'departdate' => '',
            'addtime' => time(),
            'memberid' => $member_id,
            'dingnum' => $dingnum,
            'childnum' => 0,
            'oldprice' => 0,
            'oldnum' => 0,
            'linkman' => $linkman,
            'linktel' => $linktel,
            'linkemail' => $linkemail,
            'suitid' => $suitid,
            'remark' => $remark,
            'status' => $info['status'] ?: 0,
            'source' => $source,
            'usejifen' => $useJifen,
            'needjifen' => $needJifen,
            'receiver_address_id' => $receiver_address_id,
            'receiver_address_infos' => json_encode($receiver_address_info, JSON_UNESCAPED_UNICODE),
            'express_total_price' => $express_total_price,
            'auto_close_time' => $auto_close_time, //自动关闭订单时间,
            'auto_confirm_time' => $auto_confirm_time, //自动关闭订单时间,
            'no_confirm_refund' => $no_confirm_refund,
            'refund_restriction' => $suit['refund_restriction'],//退改条件
        );
    }

    /**
     * 添加会员快递地址
     * @param $request_param
     * @param $order_info
     * @return void
     */
    public static function add_member_address($request_param, $order_info)
    {
        $province = Arr::get($request_param, 'receive_province', '');
        $city     = Arr::get($request_param, 'receive_city', '');
        $address  = Arr::get($request_param, 'receive_address', '');
        $postcode = Arr::get($request_param, 'receive_postcode', '');
        $phone    = Arr::get($request_param, 'receive_phone', '');
        $receiver = Arr::get($request_param, 'receive_receiver', '');

        $address_model           = ORM::factory('member_address');
        $address_model->address  = $address;
        $address_model->province = $province;
        $address_model->city     = $city;
        $address_model->postcode = $postcode;
        $address_model->phone    = $phone;
        $address_model->receiver = $receiver;
        $address_model->memberid = $order_info['memberid'];
        $address_model->save();
        if ($address_model->saved()) {
            $address_model->reload();
            DB::update('member_order')
                ->set(array('receiver_address_id' => $address_model->id))
                ->where('id', '=', $order_info['id'])
                ->execute();
        }
    }
}